#include "homeownermanagewidget.h"
#include "ui_homeownermanagewidget.h"
#include <QSqlQuery>
#include <QMessageBox>
#include <QDebug>
#include <QSqlError>

HomeownerManageWidget::HomeownerManageWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HomeownerManageWidget)
{
    ui->setupUi(this);
    initWindow();
    initTable();
}

HomeownerManageWidget::~HomeownerManageWidget()
{
    delete ui;
}

/**
 * @brief 初始化窗体
 */
void HomeownerManageWidget::initWindow()
{
    this->setWindowTitle("业主管理");
}

/**
 * @brief 初始化Table
 */
void HomeownerManageWidget::initTable()
{
    model = new QSqlTableModel(this);
    model->setTable("user"); //指定表
    model->setFilter("role = 3"); //指定查询条件：业主3
    model->setHeaderData(1,Qt::Horizontal,"用户名");
    model->setHeaderData(2,Qt::Horizontal,"密码");
    model->setHeaderData(3,Qt::Horizontal,"电话");
    model->setHeaderData(4,Qt::Horizontal, "地址");
    model->setHeaderData(5,Qt::Horizontal, "角色");
    model->select(); //查询
    model->setEditStrategy(QSqlTableModel::OnManualSubmit); //Model编辑策略，提交生效
    ui->tableView->setModel(model); //将模型设置到视图中
    ui->tableView->setColumnHidden(0, 1); //隐藏编号列
    ui->tableView->setColumnHidden(5, 1); //隐藏角色列
}

/**
 * @brief 添加业主
 */
void HomeownerManageWidget::on_btn_addUser_clicked()
{
    int rowNum = model->rowCount(); //获取表的最大行号
    model->insertRow(rowNum);
    model->setData(model->index(rowNum, 5), 3); //角色列，默认为3
}

/**
 * @brief 删除选中业主
 */
void HomeownerManageWidget::on_btn_deleteUser_clicked()
{
    int curRow = ui->tableView->currentIndex().row(); //获取选中行号
    model->removeRow(curRow); //删除该行
    int ok = QMessageBox::warning(this,
                                  tr("删除当前行！"),
                                  tr("你确定删除当前行吗？"),
                                  QMessageBox::Yes,
                                  QMessageBox::No);
    if (ok == QMessageBox::No) {
        model->revertAll();
    } else {
        model->submitAll();
    }
}

/**
 * @brief 提交修改操作
 */
void HomeownerManageWidget::on_btn_commit_clicked()
{
    model->database().transaction(); //开启事务操作
    if (model->submitAll()) {
        int res = model->database().commit(); //提交
        if (res == true)
        {
            QMessageBox::information(this, tr("提示"), tr("提交成功"), QMessageBox::Ok);
        }
        else
        {
            QMessageBox::warning(this, tr("警告"), tr("提交失败"), QMessageBox::Ok);
        }
    } else {
        model->database().rollback(); //回滚
        QMessageBox::warning(this,
                             tr("tableModel"),
                             tr("数据库错误：%1").arg(model->lastError().text()));
    }
}

/**
 * @brief 撤销修改操作
 */
void HomeownerManageWidget::on_btn_backout_clicked()
{
    model->revertAll();
}
